<?php

namespace app\common\library;

use think\Hook;
use think\Env;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;

/**
 * 短信验证码类
 */
class Sms
{

    /**
     * 验证码有效时长
     * @var int
     */
    protected static $expire = 300;

    /**
     * 最大允许检测的次数
     * @var int
     */
    protected static $maxCheckNums = 10;

    /**
     * 获取最后一次手机发送的数据
     *
     * @param   int    $mobile 手机号
     * @param   string $event  事件
     * @return  Sms
     */
    public static function get($mobile, $event = 'default')
    {
        $sms = \app\common\model\Sms::
        where(['mobile' => $mobile, 'event' => $event])
            ->order('id', 'DESC')
            ->find();
        Hook::listen('sms_get', $sms, null, true);
        return $sms ? $sms : null;
    }

    /**
     * 发送验证码
     *
     * @param   int    $mobile 手机号
     * @param   int    $code   验证码,为空时将自动生成4位数字
     * @param   string $event  事件
     * @param   int $type  类型1国内2国外
     * @return  boolean
     */
    public static function send($mobile, $code = null, $event = 'default',$type=1,$countryCode="")
    {
        $code = is_null($code) ? mt_rand(1000, 9999) : $code;
        $time = time();
        $ip = request()->ip();
        $sms = \app\common\model\Sms::create(['event' => $event, 'mobile' => $mobile, 'code' => $code, 'ip' => $ip, 'createtime' => $time]);

        if ( $type == 1 ) {
            $result = Hook::listen('sms_send', $sms, null, true);
        }else{
            $mobile = $countryCode.$mobile;
            // $code = "【工聯灣區】您的驗證碼".$code."，該驗證碼5分鐘內有效，請勿泄漏於他人！";
            $result = self::sendWSms($mobile,$code);
        }

        if (!$result) {
            $sms->delete();
            return false;
        }
        return true;
    }

    public static function sendWSms($phone,$code){
        AlibabaCloud::accessKeyClient(Env::get('aliems.accessKeyId'),Env::get('aliems.accessKeySecret'))
            ->regionId('cn-hangzhou')
            ->asGlobalClient();
        try {
            $result = AlibabaCloud::rpcRequest()
                ->product('Dysmsapi')
                ->host('dysmsapi.aliyuncs.com')
                ->version('2017-05-25')
                ->action('SendSms')//请求api接口名称
                ->method('POST')
                ->options([
                    'query' => [
                        "SignName" => "工联湾区",//签名
                        "TemplateCode" => "SMS_239322540",//模板code
                        "TemplateParam" => '{"code":"'.$code.'"}',//验证码
                        "PhoneNumbers" => "$phone",//发送目标手机号
                    ],
                ])
                ->request();
            $return_data = \GuzzleHttp\json_decode($result,true);
            if ( $return_data['Code'] == 'OK' ) {
                return true;
            }
            return false;

        } catch (ClientException $e) {
            // echo $e->getErrorMessage() . PHP_EOL;
            return false;
        } catch (ServerException $e) {
            // echo $e->getErrorMessage() . PHP_EOL;
            return false;
        }
    }

    /**
     * 发送通知
     *
     * @param   mixed  $mobile   手机号,多个以,分隔
     * @param   string $msg      消息内容
     * @param   string $template 消息模板
     * @return  boolean
     */
    public static function notice($mobile, $msg = '', $template = null)
    {
        $params = [
            'mobile'   => $mobile,
            'msg'      => $msg,
            'template' => $template
        ];
        $result = Hook::listen('sms_notice', $params, null, true);
        return $result ? true : false;
    }

    /**
     * 校验验证码
     *
     * @param   int    $mobile 手机号
     * @param   int    $code   验证码
     * @param   string $event  事件
     * @return  boolean
     */
    public static function check($mobile, $code, $event = 'default')
    {
        $time = time() - self::$expire;
        $sms = \app\common\model\Sms::where(['mobile' => $mobile, 'event' => $event])
            ->order('id', 'DESC')
            ->find();
        if ($sms) {
            if ($sms['createtime'] > $time && $sms['times'] <= self::$maxCheckNums) {
                $correct = $code == $sms['code'];
                if (!$correct) {
                    $sms->times = $sms->times + 1;
                    $sms->save();
                    return false;
                } else {
                    $result = Hook::listen('sms_check', $sms, null, true);
                    return $result;
                }
            } else {
                // 过期则清空该手机验证码
                self::flush($mobile, $event);
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * 清空指定手机号验证码
     *
     * @param   int    $mobile 手机号
     * @param   string $event  事件
     * @return  boolean
     */
    public static function flush($mobile, $event = 'default')
    {
        \app\common\model\Sms::
        where(['mobile' => $mobile, 'event' => $event])
            ->delete();
        Hook::listen('sms_flush');
        return true;
    }
}
